from functools import wraps
from datetime import datetime

def format_datetime(func):
    """时间格式化装饰器"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        value = func(*args, **kwargs)
        if isinstance(value, datetime):
            return value.strftime('%Y-%m-%d %H:%M:%S')
        return value
    return wrapper


class TimestampFormatterMixin:
    """时间格式化混入类"""
    @format_datetime
    def format_timestamp(self, timestamp):
        return timestamp if timestamp else None


class StatusFieldsMixin:
    """状态字段混入类"""
    def get_latest_status(self, obj):
        """获取最新状态"""
        return obj.statuses.last()

    def get_status_field(self, obj, field_name):
        """获取状态字段通用方法"""
        latest_status = self.get_latest_status(obj)
        return getattr(latest_status, field_name) if latest_status else None
    

class PlatformMappingMixin:
    """平台映射混入类"""
    PLATFORM_MAPPING = {
        'xhs': '小红书',
        'dy': '抖音',
        'bili': '哔哩哔哩',
        'wb': '微博',
        'ks': '快手',
        'tieba': '百度贴吧',
        'zhihu': '知乎'
    }

    def get_platform_display(self, platform_code):
        """获取平台显示名称"""
        return self.PLATFORM_MAPPING.get(platform_code, platform_code)

    def get_platform_code(self, display_name):
        """获取平台代码"""
        reverse_mapping = {v: k for k, v in self.PLATFORM_MAPPING.items()}
        return reverse_mapping.get(display_name, display_name)


class CrawlerTypeMappingMixin:
    """爬虫类型映射混入类"""
    CRAWLER_TYPE_MAPPING = {
        'search': '关键词搜索',
        'detail': '内容详情',
        'creator': '创作者信息'
    }

    def get_crawler_display(self, type_code):
        """获取爬虫类型显示名称"""
        return self.CRAWLER_TYPE_MAPPING.get(type_code, type_code)

    def get_crawler_type_code(self, display_name):
        """获取爬虫类型代码"""
        reverse_mapping = {v: k for k, v in self.CRAWLER_TYPE_MAPPING.items()}
        return reverse_mapping.get(display_name, display_name)